const Game = function() {
    let game = {}
    game.timer = 0
    game.timer1 = 0
    game.actionTimers = {}
    game.score = 0
    game.lineNumber = 0
    game.level = 1
    game.width = 10
    game.height = 24
    game.fps = 0
    game.rate = 30
    game.currentBlock = Block()
    game.nextBlock = Block()
    game.map = createMap(game.width, game.height)
    game.currentCoors = loadBlock(game.map, game.currentBlock)
    game.block = game.currentBlock.block[game.currentBlock.state]
    game.listeners = {}
    game.canLock = true
    game.pressing = false
    game.buttonsTouch = {
        left: false,
        right: false,
        down: false,
    }
    game.reset = function() {
        game.map = createMap(game.width, game.height)
        game.currentBlock = Block()
        game.nextBlock = Block()
        game.score = 0
        game.lineNumber = 0
        game.level = 1
        game.currentCoors = loadBlock(game.map, game.currentBlock)
        clearTimeout(game.timer)
        clearTimeout(game.timer1)
        game.run()
    }
    game.runloop = function() {
        let keys = Object.keys(game.buttonsTouch)
        for (let i = 0; i < keys.length; i++) {
            let k = keys[i]
            if (game.buttonsTouch[k]) {
                move(game, k)
            }
        }
        game.timer1 = setTimeout(() => {
            game.runloop()
        }, 1000 / game.rate)

    }
    game.loadLevel = function() {
        let l = levels[game.level - 1]
        game.fps = l.fps
        game.rate = l.rate
    }
    game.run = function() {
        game.runloop()
        game.loadLevel()
    }
    game.updateLevel = function() {
        let level = Math.floor(game.score / levelScores) + 1
        if (level > levels.length) {
            level = levels.length
        }
        game.level = level
        game.loadLevel()
        updateLevel(game.level)
    }
    game.moveLeft = function() {
        move(game, 'left')
        game.actionTimers.left = setTimeout(() => {
            game.buttonsTouch.left = true
        }, 100)
    }
    game.moveRight = function() {
        move(game, 'right')
        game.actionTimers.right = setTimeout(() => {
            game.buttonsTouch.right = true
        }, 100)
    }
    game.moveDown = function() {
        move(game, 'down')
        game.actionTimers.down = setTimeout(() => {
            game.buttonsTouch.down = true
        }, 100)
    }
    game.move = function(direction) {
        if (!game.pressing) {
            move(game, direction)
            game.actionTimers[direction] = setTimeout(() => {
                game.buttonsTouch[direction] = true
            }, 100)
        }
        game.pressing = true

    }
    return game
}